package com.theta.gateway.facade.web.component.filter;


import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import com.theta.gateway.infra.common.context.GatewayRequestContext;
import com.theta.gateway.infra.common.utils.GatewayRequestUtil;

import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;


/**
 * 全局过滤器-统一处理请求中的参数
 * @author theta
 *
 */
@Slf4j
@Component
public class ParamFormatGlobalFilter implements GlobalFilter, Ordered {

    
	/**
	 * 过滤器执行顺序-值越小，优先级越高
	 */
	@Override
	public int getOrder() {
		return -1;
	}

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		ServerHttpRequest request=exchange.getRequest();
		String url = request.getURI().getPath();
		MediaType mediaType = request.getHeaders().getContentType();
		 String method = request.getMethodValue();
		log.info("ParamFormatGlobalFilter....filter..{},mediaType: {},method: {}",url,mediaType,method);
		
		GatewayRequestContext gatewayContext = new GatewayRequestContext();
        String path = request.getPath().pathWithinApplication().value();
        gatewayContext.setPath(path);
        gatewayContext.getFormData().addAll(request.getQueryParams());
        gatewayContext.setIpAddress(String.valueOf(request.getRemoteAddress()));
        HttpHeaders headers = request.getHeaders();
        gatewayContext.setHeaders(headers);
        log.info("HttpMethod:{},Url:{}", request.getMethod(), request.getURI().getRawPath());

        /// 注意，因为webflux的响应式编程 不能再采取原先的编码方式 即应该先将gatewayContext放入exchange中，否则其他地方可能取不到
        /**
         * save gateway context into exchange
         */
        exchange.getAttributes().put(GatewayRequestContext.CACHE_GATEWAY_CONTEXT, gatewayContext);

        // 处理参数
        MediaType contentType = headers.getContentType();
        long contentLength = headers.getContentLength();
        log.info("RequestParamsFormatRouteFilter mediaType: {},contentLength:{}",mediaType,contentLength);
        if (contentLength > 0) {
            if (MediaType.APPLICATION_JSON.equals(contentType) || MediaType.APPLICATION_JSON_UTF8.equals(contentType)) {
            	return GatewayRequestUtil.readBody(exchange, chain, gatewayContext);
            }
            if (MediaType.APPLICATION_FORM_URLENCODED.equals(contentType)) {
                return GatewayRequestUtil.readFormData(exchange, chain, gatewayContext);
            }
        }
		return chain.filter(exchange);
	}
	
	
	
	
	

    
    
   
    

}
